package com.lx.service;

import org.apache.commons.lang3.Validate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 段誉
 * @create 2020-06-12 14:44
 */
public class UserService {
  private JdbcTemplate jdbcTemplate;

  public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }

  public void insert(Integer id, String name) {
    String sql = "INSERT INTO user VALUES (?, ?)";
    int res = jdbcTemplate.update(sql, id, name);
    Validate.isTrue(res > 0, "添加失败");
  }

  public List selectAll() {
    String sql = "SELECT id, name FROM user";
    List<Map<String, Object>> data = jdbcTemplate.queryForList(sql);
    return data;
  }

  public Object selectById(Integer id) {
    String sql = "SELECT id, name FROM user WHERE id=?";
    Map data = jdbcTemplate.queryForObject(sql, new Object[]{1}, new RowMapper<Map>() {
      public Map mapRow(ResultSet rs, int rowNum) throws SQLException {
        Map<String, Object> data = new HashMap<String, Object>();
        data.put("id", rs.getInt("id"));
        data.put("name", rs.getString("name"));
        return data;
      }
    });
    return data;
  }

  public void updateById(String name, Integer id) {
    String sql = "UPDATE user SET name=? WHERE id=?";
    int res = jdbcTemplate.update(sql, name, id);
    Validate.isTrue(res > 0, "修改失败");
  }

  public void deleteById(Integer id) {
    String sql = "DELETE FROM user WHERE id=?";
    int res = jdbcTemplate.update(sql, id);
    Validate.isTrue(res > 0, "删除失败");
  }

}
